import useDrawingBoard from "@/store/modules/drawingBoard";
/**
 * 键盘上下左右平移移动节点
 * @param { HTMLElement }  flowGraph  antv x6 元素
 * @param { number } _width 可移动范围内画布的宽
 * @param { number } _height 可移动范围内画布的高
 */
let bool: boolean = false;
let timer: any = null;
let nodeList: any = [];
export const addNodeTranslation = (flowGraph: any, _width: number, _height: number) => {
  const drawingBoardStore = useDrawingBoard();
  bool = false;
  flowGraph.on("node:selected", () => {
    bool = false;
    timer = null;
    nodeList = [];
  });
  flowGraph.on("node:unselected", ({ node }) => {
    if (!node.id?.startsWith("n")) return;
    const { x, y } = node?.position();
    const xSum = Math.abs(x);
    const ySum = Math.abs(y);
    const widthGraph: number = Math.ceil(_width);
    const heightGraph: number = Math.ceil(_height);
    if (xSum > widthGraph || ySum > heightGraph || x < 0 || y < 0)
      return ElMessage.error(
        `您添加的画布节点【x坐标: ${x}】【y坐标: ${y}】已超出范围，规定范围是：${_width} * ${_height}内`
      );
    const _row = node?.getData();
    _row.x = x;
    _row.y = y;
    if (bool) {
      nodeList.push(_row);
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
        // const listPromise = nodeList.map((item: any) => {
        //   return getNodes(item, mapId, false);
        // });
        // Promise.all(listPromise).finally(() => {
        //   canvansMapStore.changeNodes("node");
        //   nodeList = [];
        // });
        nodeList = [];
      }, 500);
    }
    flowGraph.unbindKey(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"], "keydown");
  });
  // 监听选中的值
  flowGraph.on("selection:changed", ({ selected }) => {
    drawingBoardStore.setNodeSelectedList(selected);
    const listNode: any = [];
    selected.forEach((item: any) => {
      if (!item.id?.startsWith("n")) return;
      const { x, y } = item?.position();
      const xSum = Math.abs(x);
      const ySum = Math.abs(y);
      const widthGraph: number = Math.ceil(_width);
      const heightGraph: number = Math.ceil(_height);
      if (xSum > widthGraph || ySum > heightGraph || x < 0 || y < 0)
        return ElMessage.error(
          `您添加的画布节点【x坐标: ${x}】【y坐标: ${y}】已超出范围，规定范围是：${_width} * ${_height}内`
        );
      listNode.push(item);
    });
    bindKeyGet(flowGraph, listNode);
  });
};

// 批量绑定
const bindKeyGet = (flowGraph: any, nodeList: any) => {
  flowGraph.bindKey(
    ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"],
    (e: any) => {
      bool = true;
      const step = 1;
      nodeList.forEach((item: any) => {
        switch (e.key) {
          case "ArrowUp":
            item.translate(0, -step);
            break;
          case "ArrowDown":
            item.translate(0, step);
            break;
          case "ArrowLeft":
            item.translate(-step, 0);
            break;
          case "ArrowRight":
            item.translate(step, 0);
            break;
        }
      });
    },
    "keydown"
  );
};
